import { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, MessagePlugin, Input, Checkbox, Button, FormInstanceFunctions, SubmitContext } from 'tdesign-react';
import { LockOnIcon, UserIcon, BrowseOffIcon, BrowseIcon } from 'tdesign-icons-react';
import classnames from 'classnames';

import Style from './index.module.less';
import { getMenu, login } from '@/api';
import menuStore from '@/store/menu';

const { FormItem } = Form;

export type ELoginType = 'password' | 'phone' | 'qrcode';

export default function Login() {
  const [loginType, changeLoginType] = useState<ELoginType>('password');
  const [showPsw, toggleShowPsw] = useState(false);

  const { setMenu } = menuStore();

  const formRef = useRef<FormInstanceFunctions>();
  const navigate = useNavigate();

  const onSubmit = async (e: SubmitContext) => {
    if (e.validateResult === true) {
      try {
        console.log('e', e.fields);
        login(e.fields).then((res: any) => {
          MessagePlugin.success('登录成功');
          console.log('res', res);
          localStorage.setItem('token', res.token);
          // navigate('/');
          return getMenu({ username: res.username })
        }).then(value => {
          setMenu((value as any).menu as any);
          setTimeout(() => {
            navigate('/');
          }, 1000);
        })

      } catch (e) {
        MessagePlugin.error('登录失败');
      }
    }
  };

  const switchType = (val: ELoginType) => {
    formRef.current?.reset?.();
    changeLoginType(val);
  };

  return (
    <div>
      <Form
        ref={formRef}
        className={classnames(Style.itemContainer, `login-${loginType}`)}
        labelWidth={0}
        onSubmit={onSubmit}
      >
        <FormItem name='username' rules={[{ required: true, message: '账号必填', type: 'error' }]}>
          <Input size='large' placeholder='请输入账号：admin' prefixIcon={<UserIcon />}></Input>
        </FormItem>
        <FormItem name='password' rules={[{ required: true, message: '密码必填', type: 'error' }]}>
          <Input
            size='large'
            type={showPsw ? 'text' : 'password'}
            clearable
            placeholder='请输入登录密码：123456'
            prefixIcon={<LockOnIcon />}
            suffixIcon={
              showPsw ? (
                <BrowseIcon onClick={() => toggleShowPsw((current) => !current)} />
              ) : (
                <BrowseOffIcon onClick={() => toggleShowPsw((current) => !current)} />
              )
            }
          />
        </FormItem>
        <div className={classnames(Style.checkContainer, Style.rememberPwd)}>
          <Checkbox>记住账号</Checkbox>
          <span className={Style.checkContainerTip}>忘记账号？</span>
        </div>
        {loginType !== 'qrcode' && (
          <FormItem className={Style.btnContainer}>
            <Button block size='large' type='submit'>
              登录
            </Button>
          </FormItem>
        )}
        <div className={Style.switchContainer}>
          {loginType !== 'password' && (
            <span className='tip' onClick={() => switchType('password')}>
              使用账号密码登录
            </span>
          )}
        </div>
      </Form>
    </div>
  );
}
